package com.ljx.poi.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 李捷禧
 * Date: 2023/7/27
 * ClassName: ExcelUtils
 */

public class ExcelUtils {

    public static void exportExcel(String fileName, HttpServletResponse response, Class<?> pojoClass, List<?> list, String title) {
        ExportParams params = new ExportParams();
        //设置样式
        params.setStyle(ExcelStyleUtil.class);
        //设置sheet名
        params.setSheetName(title);
        Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setCharacterEncoding("utf-8");
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            // 一个自定义枚举 错误信息的
            System.out.println(e);
        }
    }
}

